package com.smallstep.hystrix.utils;

import com.smallstep.hystrix.entity.FFPathPattern;
import org.springframework.http.HttpMethod;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李俊
 */
public class UrlUtil {

    public static String getHost(URL url) throws MalformedURLException {
        return url.getPort() >= 0 ? url.getHost() + ":" + url.getPort() : url.getHost();
    }

    public static  URL format(String url) throws MalformedURLException {
        if (!isStartsWithHttp(url)) {
            url = "http://" + url;
        }

        return new URL(url);
    }

    private static boolean isStartsWithHttp(String urlStr) {
        urlStr = urlStr.trim().toLowerCase();
        return urlStr.startsWith("http://") || urlStr.startsWith("https://");
    }

    public static List<FFPathPattern> splitPathPatterns(String pathPatternsStr) {
        List<FFPathPattern> pathPatterns = new ArrayList();
        String[] pathPatternArray = pathPatternsStr.split(",");

        for(int i = 0; i < pathPatternArray.length; i++) {
            String pathPattern = pathPatternArray[i];
            String[] subPathPatterns = pathPattern.trim().split("\\$", 2);
            if (subPathPatterns.length == 1) {
                pathPatterns.add(new FFPathPattern((HttpMethod)null, subPathPatterns[0].trim()));
            } else {
                pathPatterns.add(new FFPathPattern(HttpMethod.resolve(subPathPatterns[0].trim().toUpperCase()), subPathPatterns[1].trim()));
            }
        }

        return pathPatterns;
    }
}
